﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using ScapiRenderFieldResult = global::Sitecore.Xml.Xsl.RenderFieldResult;
using System.Web.Mvc;
using System.Linq.Expressions;

namespace Pocahontas.Sitecore.Mvc
{
	public class SitecoreHtmlLinkString<TModel> : IHtmlString
	{
		private readonly HtmlHelper<TModel> _htmlHelper;
		private LinkedList<IHtmlString> _htmlStringList;
		private Func<string, string> _renderer;

		public SitecoreHtmlLinkString(HtmlHelper<TModel> htmlHelper, Func<string, string> renderer)
		{
			_htmlHelper = htmlHelper;
			_renderer = renderer;
			_htmlStringList = new LinkedList<IHtmlString>();
		}

		private SitecoreHtmlLinkString<TModel> Html(IHtmlString html)
		{
			_htmlStringList.AddLast(html);

			return this;
		}

		public SitecoreHtmlLinkString<TModel> FieldIfEmpty<TProperty>(Expression<Func<TModel, TProperty>> expression, object htmlAttributes = null)
		{
			return Html(_htmlHelper.FieldFor<TModel, TProperty>(expression, htmlAttributes));
		}

		public SitecoreHtmlLinkString<TModel> ImageIfEmpty<TProperty>(Expression<Func<TModel, TProperty>> expression, object htmlAttributes = null)
		{
			return Html(_htmlHelper.ImageFor<TModel, TProperty>(expression, htmlAttributes));
		}

		string IHtmlString.ToHtmlString()
		{
			StringBuilder builder = new StringBuilder();

			foreach (IHtmlString htmlString in _htmlStringList)
			{
				builder.Append(htmlString);
			}

			return _renderer(builder.ToString());
		}
	}
}
